package com.liao.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liao.common.Result;
import com.liao.entity.BookCategory;
import com.liao.service.BookCategoryService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * 图书分类控制器
 */
@RestController
@RequestMapping("/categories")
public class BookCategoryController {

    @Resource
    private BookCategoryService bookCategoryService;

    /**
     * 获取图书分类分页列表
     *
     * @param current 当前页
     * @param size    每页大小
     * @param name    分类名称（可选）
     * @return 分页图书分类列表
     */
    @GetMapping("/page")
    public Result<Page<BookCategory>> getCategoryPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name) {
        Page<BookCategory> page = new Page<>(current, size);
        Page<BookCategory> categoryPage = bookCategoryService.getCategoryPage(page, name);
        return Result.success(categoryPage);
    }

    /**
     * 获取所有分类（不分页）
     *
     * @return 所有分类列表
     */
    @GetMapping("/all")
    public Result<List<BookCategory>> getAllCategories() {
        List<BookCategory> list = bookCategoryService.list();
        return Result.success(list);
    }

    /**
     * 添加图书分类
     *
     * @param bookCategory 图书分类信息
     * @return 添加结果
     */
    @PostMapping
    public Result<Boolean> addCategory(@RequestBody @Valid BookCategory bookCategory) {
        boolean result = bookCategoryService.addCategory(bookCategory);
        return Result.success(result);
    }

    /**
     * 修改图书分类
     *
     * @param bookCategory 图书分类信息
     * @return 修改结果
     */
    @PutMapping("/{id}")
    public Result<Boolean> updateCategory(@PathVariable Long id, @RequestBody @Valid BookCategory bookCategory) {
        bookCategory.setId(id);
        boolean result = bookCategoryService.updateCategory(bookCategory);
        return Result.success(result);
    }

    /**
     * 删除图书分类
     *
     * @param id 分类ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteCategory(@PathVariable Long id) {
        boolean result = bookCategoryService.deleteCategory(id);
        return Result.success(result);
    }

    /**
     * 根据ID获取分类名称
     *
     * @param id 分类ID
     * @return 分类名称
     */
    @GetMapping("/{id}/name")
    public Result<String> getCategoryNameById(@PathVariable Long id) {
        BookCategory category = bookCategoryService.getById(id);
        if (category == null) {
            return Result.error("分类不存在");
        }
        return Result.success(category.getName());
    }
}